<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="安检时间:" :table-form-merge="2">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item class="merge-item">
        <el-select
          v-model="query.orgType"
          style="width: 180px; margin-right: 2px;"
        >
          <el-option label="安检人机构" value="security" />
          <el-option label="责任机构" value="guarantee" />
        </el-select>
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params="{
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled'
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>

      <el-form-item label="安检人:" prop="checkUser">
        <el-select v-model="query.checkUser" placeholder="请选择">
          <el-option
            v-for="item in checkUserMap"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="merge-item">
        <el-select
          v-model="query.soType"
          style="width: 180px; margin-right: 2px;"
        >
          <el-option label="订单号" value="orderCode" />
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="客户地址" value="csmAddress" />
          <el-option label="安检单号" value="checkId" />
        </el-select>
        <el-input v-model="soTypeParams" />
      </el-form-item>

      <el-form-item label="安检类型:">
        <el-select v-model="query.checkType" placeholder="请选择">
          <el-option label="请选择" :value="0" />
          <el-option
            v-for="item in checkTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select v-model="query.csmTypes" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="安检项:" prop="csmItem">
        <el-tree-select
          v-model="query.itemDetailIds"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :tree-params="{
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'value',
              label: 'label'
            },
            data: gasCheckItemArray
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>

      <el-form-item label="状态:" prop="checkStatus">
        <el-select v-model="query.checkStatus" placeholder="请选择">
          <el-option label="请选择" :value="0" />
          <el-option
            v-for="item in checkStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="隐患等级:" prop="warnLevel">
        <el-select v-model="query.warnLevel" placeholder="请选择">
          <el-option
            v-for="item in warnLevelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="安检照片:" :table-form-merge="2" prop="imageName">
        <el-radio-group v-model="query.imageName">
          <el-radio label="all">全部</el-radio>
          <el-radio label="yes">有</el-radio>
          <el-radio label="no">无</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-slot:btns>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <el-button
        type="primary"
        icon="el-icon-s-platform"
        @click="batchExamine"
      >批量审核</el-button>
      <el-button
        type="primary"
        icon="el-icon-upload2"
        @click="batchExp"
      >导出</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
      @selection-change="handleSelectionChange"
    />

    <securityOrderInfo ref="securityOrderInfo" :warn-level-map="warnLevelMap " />
    <batchExamine ref="batchExamine" />
    <rectification ref="rectification" />
  </div>
</template>

<script>
  import rectification from './components/rectification.vue'
  import securityOrderInfo from '../../components/SecurityCheckDetail'
  import batchExamine from './components/batchExamine.vue'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap, parseTime } from '@/utils'
  import {
    gasCheckBillQueryList,
    gasCheckUserQueryList,
    gasCheckBillExport,
    queryExportDomain,
    gasCheckBillReverse,
    gasCheckItemList
  } from '@/api'
  export default {
    name: 'securityOrderManage',
    components: { securityOrderInfo, batchExamine, rectification },
    data() {
      return {
        actionColWidth: 80,
        mode: 1,
        treeData: [],
        gasCheckItemArray: [],
        exportDomain: '',
        qtype: 1,
        txt: '',
        soTypeParams: '',
        checkUserMap: [],
        multipleSelection: [],
        customerTypeMap: [
          { value: 1, desc: '居民用户', key: 'Resident_user' },
          { value: 2, desc: '商业用户', key: 'Business_user' },
          { value: 4, desc: '工业用户', key: 'GY_user' }
        ],
        checkTypeMap: [
          { value: 1, desc: '随单安检', key: 'SD' },
          { value: 2, desc: '定期安检', key: 'JH' }
        ],
        warnLevelMap: [
          { value: 0, desc: '无隐患', key: 'ZOO' },
          { value: 1, desc: '一般隐患', key: 'YJ' },
          { value: 2, desc: '严重隐患', key: 'EJ' },
          { value: 3, desc: '隐患', key: 'SJ' },
          { value: 4, desc: 'level4', key: 'SIJ' },
          { value: 5, desc: 'level5', key: 'WJ' }
        ],
        checkStatusMap: [
          { value: 1, desc: '未审核', key: 'UN_CHECK' },
          { value: 2, desc: '合格', key: 'VALID' },
          { value: 3, desc: '不合格', key: 'INVALID' }
        ],
        query: {
          soType: 'csmPhone',
          checkType: 0,
          date: [new Date().setDate(1), new Date()],
          orgType: 'guarantee',
          csmTypes: [0],
          orgSNNo: '001000000000000000000',
          imageName: 'all',
          checkDt: new Date().setDate(1),
          checkDtEnd: new Date()
        },
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            type: 'selection'
          },
          { label: '安检单号', prop: 'checkId' },
          { label: '责任机构', width: 150, prop: 'orgName' },
          { label: '安检人', align: 'center', prop: 'checkUser' },
          { label: '安检机构', width: 150, prop: 'checkOrgName' },
          {
            label: '安检时间',
            width: 150,
            prop: 'checkDt',
            render: (h, { row }) => (
              <span>
                {row.checkDt &&
                parseTime(row.checkDt, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
          },
          {
            prop: 'csmType',
            align: 'center',
            label: '客户类型',
            render: (h, { row }) => (
              <span>
                {row.csmType &&
                formatColumnMap(
                  this.customerTypeMap,
                  'value',
                  row.csmType,
                  'desc'
                )}
              </span>
            )
          },
          { label: '客户编号', prop: 'csmCode' },
          { label: '客户名称', align: 'center', prop: 'csmName' },
          { label: '客户地址', width: 150, prop: 'csmAddress' },
          { label: '联系电话', width: 150, prop: 'csmPhone' },
          {
            label: '安检类型',
            align: 'center',
            prop: 'checkType',
            render: (h, { row }) => (
              <span>
                {row.checkType &&
                formatColumnMap(
                  this.checkTypeMap,
                  'value',
                  row.checkType,
                  'desc'
                )}
              </span>
            )
          },
          {
            label: '隐患等级',
            align: 'center',
            prop: 'warnLevel',
            render: (h, { row }) => row.warnLevel ? <el-link onClick={() => this.openDangerDetail(row)}>{row.warnLevel}</el-link> : <span>{formatColumnMap(this.warnLevelMap, 'value', row.warnLevel, 'desc')}</span>
          },
          { label: '关联订单号', width: 100, prop: 'orderCode' },
          {
            label: '状态',
            align: 'center',
            prop: 'checkStatus',
            render: (h, { row }) => (
              <span>
                {row.checkStatus &&
                formatColumnMap(
                  this.checkStatusMap,
                  'value',
                  row.checkStatus,
                  'desc'
                )}
              </span>
            )
          },
          { label: '备注', width: 150, prop: 'remark' },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-link size='mini' underline={false} onClick={() => this.openOrderInfo(row, $index)}>
                    详情
                  </el-link>
                  {row.checkStatus === 1 && <el-link size='mini' underline={false} onClick={() => this.openOrderExamine(row, $index)}>
                    审核
                  </el-link>}
                  {row.checkStatus !== 1 && <el-link size='mini' underline={false} onClick={() => this.revokeExamine(row, $index)}>
                    反审核
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    watch: {
      'query.orgSNNo': function(val) {
        this.queryGasCheckItem()
      },
      'query.checkType': function(val) {
        this.queryGasCheckItem()
      },
      'query.csmTypes': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.csmTypes = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.csmTypes.splice(val.indexOf(0), 1)
        }
        if (this.query.csmTypes.length === this.customerTypeMap.length) this.query.csmTypes = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {
      await this.getTreeData()
      this.getCheckUser()
      this.getExportDomain()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        // const res = await organizationQueryList({})
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then(res => {
          console.log(res)
          this.exportDomain = res.data
        })
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },

      async fetchData({ currentPage, pageSize }) {
        const query = this.getQuery()
        query.pageIndex = currentPage
        query.pageSize = pageSize
        if (this.query.csmTypes[0] === 0) query.csmTypes = []
        const res = await gasCheckBillQueryList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 安检人
      getCheckUser() {
        gasCheckUserQueryList().then(res => {
          this.checkUserMap = res.data
        })
      },
      queryGasCheckItem() {
        gasCheckItemList({
          orgSNNo: this.query.orgSNNo,
          csmType: 1,
          checkType: this.query.checkType
        }).then(res => {
          const gasCheckItemArray = res.data
          gasCheckItemArray.map(item => {
            item.detailList.map(item2 => {
              item2.label = item2.itemDetailName
              item2.value = item2.itemDetailId
            })
            item.children = item.detailList
            item.label = item.itemName
            item.value = item.itemId
          })
          this.gasCheckItemArray = gasCheckItemArray
        })
      },
      revokeExamine(row) {
        this.$confirm(
          `本操作将清空该地址的最后一次安检时间，是否继续？`,
          '操作提示',
          {
            type: 'warning'
          }
        ).then(() => {
          gasCheckBillReverse({
            checkIds: row.checkId
          }).then(res => {
            if (res.success) {
              this.$message({
                message: '操作成功!',
                type: 'success'
              })
              this.search()
            } else {
              this.$message({
                message: '操作失败！',
                type: 'error'
              })
            }
          })
        })
      },
      // 批量审核
      batchExamine() {
        const multipleSelection = this.multipleSelection
        if (multipleSelection.length < 1) {
          this.$alert('请至少选择一个安检单进行批量审核！', '提示', {
            type: 'info',
            confirmButtonText: '确定'
          })
          return
        }
        this.$refs.batchExamine.open(multipleSelection)
      },
      // 隐患详情
      warnInfo(row) {
        this.$refs.rectification.open(row)
      },
      // 导出
      batchExp() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          const query = this.getQuery()
          gasCheckBillExport({
            paramInfo: query,
            kv: str // 表格列
          }).then(res => {
            window.open(
              `${this.exportDomain}/page/export/frame?key=${res.data}`,
              '_blank'
            )
          })
        })
      },
      // 安检单详情
      async openOrderInfo(row) {
        await this.$refs.securityOrderInfo.open(row, 'info')
        this.$refs.lbTable.fetch()
      },
      async openOrderExamine(row) {
        await this.$refs.securityOrderInfo.open(row, 'examine')
        this.$refs.lbTable.fetch()
      },
      async scoresMerge() {},
      async infoCircul() {},
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reset() {
        this.$refs.form.resetFields()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      getQuery() {
        const query = { ...this._getQuery(this.query) }
        if (query.date && query.date.length > 0) {
          query.checkDt = query.date[0]
          query.checkDtEnd = query.date[1]
        }
        delete query.date
        switch (this.query.soType) {
        case 'orderCode':
          query.orderCode = this.soTypeParams
          break
        case 'csmCode':
          query.csmCode = this.soTypeParams
          break
        case 'csmName':
          query.csmName = this.soTypeParams
          break
        case 'csmAddress':
          query.csmAddress = this.soTypeParams
          break
        case 'checkId':
          query.checkId = this.soTypeParams
          break
        }
        delete query.soType
        return query
      },
      // 点击隐患等级
      openDangerDetail() {},
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: start;
}
</style>
